<template>
    <div class="chatContainer">
        <ChatList @chatUserChange="chatUserChange" :currentSelect="currentChatIndex" :chatList="props.chatList"></ChatList>
        <ChatContent v-if="currentChatIndex != -1"
                    :chatRecords="chatRecords"
                    :friendName="currentChatFriendName"
                    :relationshipId="currentRelationshipId"
                    @sendMessage="sendMessage"></ChatContent>
    </div>
</template>
<script setup lang="ts">
import ChatList from '@/components/ChatList.vue';
import ChatContent from '@/components/content/ChatContent.vue';
import type { ChatRecord, ChatUserInfo } from '@/types';
import { ref ,  toRaw} from 'vue';
import bus from '@/bus';
import lisener from '@/listener';
import chatUserapi from '@/api/chatUser'
const props = defineProps<{
    chatList:Array<ChatUserInfo>
    allChatRecords:Map<string,any>
}>()
const currentChatIndex = ref<number>(-1)
const chatRecords = ref<Array<ChatRecord>>([])
const currentChatFriendName = ref('')
const currentRelationshipId = ref('')
bus.on('fetchNewTenChatRecord',() => {

    
    const current = props.allChatRecords.get(currentRelationshipId.value).current++
    const total = props.allChatRecords.get(currentRelationshipId.value).totalNumberOfRecords
    chatUserapi.fetchChatRecords(currentRelationshipId.value,current.toString(),total).then(res => {
        console.log(res.data.records);   
        const records = res.data.records as Array<any>
        records.reverse()
        records.forEach(element => {
            (props.allChatRecords.get(currentRelationshipId.value).records as Array<any> ).unshift( element )
        }); 
        
        const crs = props.allChatRecords.get(currentRelationshipId.value).records as Array<ChatRecord>
        chatRecords.value = crs
    })
})
const chatUserChange = (index:number) => {
    currentChatIndex.value = index
    currentChatFriendName.value = props.chatList[index].friendName
    currentRelationshipId.value = props.chatList[index].id
    const crs = props.allChatRecords.get(props.chatList[index].id).records as Array<ChatRecord>
    chatRecords.value = crs
    
}
const sendMessage = (record:ChatRecord) => {
    const date = new Date()
    props.chatList.forEach(x => {
        if(x.id == record.relationshipId) {
            x.lastDate = date.getHours() + ":" + date.getMinutes()
            x.lastMessage = record.content.includes("<img ")?'[图片]' : record.content
        }
    })
    record.date = new Date()
    props.allChatRecords.get(record.relationshipId).records.push(record)
}

</script>
<style scoped>
.chatContainer{
    flex: 1;
    display: flex;
    flex-direction: row;
}
</style>